package com.liupaik.pennmarketplace;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ReplyThread extends Activity {
	
	// Declare our Views, so we can access them later
	//private TextView title;
	private TextView rThread;
	private TextView title;
	private EditText reply;
	private Button btnReply;
	private TextView lblResult;
	
	private String id;
	private String U_id;
	private String P_id;
	private String cat;
	
	//private String t;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.thread);

		// Get the EditText and Button References
		//title = (TextView)findViewById(R.id.title);
		rThread = (TextView)findViewById(R.id.thread);
		title = (TextView)findViewById(R.id.originalPost);
		lblResult = (TextView)findViewById(R.id.result);
		
		reply = (EditText)findViewById(R.id.reply);
		btnReply = (Button)findViewById(R.id.reply_button);
		
		//IF PARAMETERS HAVE BEEN SUCCESSFULLY PASSED
		Bundle extras = getIntent().getExtras();
		if(extras !=null)
		{
			//title.setText(titleB);
			
			//textB = extras.getString("text");
			//text.setText(textB);
			
			//timeB = extras.getString("time");
			//time.setText("Date Posted: " + timeB);
			
	        SharedPreferences user = getSharedPreferences("Users", MODE_PRIVATE);
	        id = user.getString("CurrentUser", null);
	        
			U_id = extras.getString("U_id");
			P_id = extras.getString("P_id");
			cat = extras.getString("cat");
			
		}
		else{
			lblResult.setText("Error getting data!");
		}
		
		String t = getThread(id,U_id,P_id);
		
		if(t.equals("Error in connecting...")){
//			new AlertDialog.Builder(ReplyThread.this)
//			.setMessage(t)  
//			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//				public void onClick(DialogInterface dialog, int id) {
//				}
//			})
//			.show();
		}
		
		else if(t.equals("Error in obtaining data...")){
//			new AlertDialog.Builder(ReplyThread.this)
//			.setMessage(t)  
//			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//				public void onClick(DialogInterface dialog, int id) {								
//				}
//			})
//			.show();
		}
		
		else if(t.equals("No thread exists")){
//			new AlertDialog.Builder(ReplyThread.this)
//			.setMessage(t)  
//			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//				public void onClick(DialogInterface dialog, int id) {
//				}
//			})
//			.show();
		}
		
		else{
			//list = (ListView)findViewById(R.id.list);
			try{
				JSONArray jArray = new JSONArray(t);
				
				JSONObject firstPost = jArray.getJSONObject(0);
				
				String user = getUsername(firstPost.getString("U_id"));
				String name[];
				name = user.split("@");
				
				title.setText("Original Post by "+name[0]+": " + firstPost.getString("title") + "\n("+firstPost.getString("time")+")");
				//rThread.append("Original Post: " + firstPost.getString("title") + " ("+firstPost.getString("time")+")\n\n");
				
				
				for(int i=jArray.length()-1;i>0;i--){
					JSONObject json_data = jArray.getJSONObject(i);
					//String L_id = json_data.getString("L_id");
					//String cat = json_data.getString("cat");
					//String title = json_data.getString("title");
					String text = json_data.getString("text");
					String R_id = json_data.getString("U_id");
					String time = json_data.getString("time");
					//listings.append(L_id + " | " + cat + " | " + title + " | " + text + " | " + U_id + " | " + time + "\n");
					
					user = getUsername(R_id);
					name = user.split("@");
					
					if(R_id.equals(id)){
						rThread.append("You replied: " + text + "\n("+ time + ")\n\n");
					}
					else{						
						rThread.append(name[0] + " replied: " + text + "\n("+ time + ")\n\n");
					}
					//listings.add(new Listing(L_id,"",U_id,cat,title,text,time));
				}
			}
			catch(JSONException e){
//				new AlertDialog.Builder(ReplyThread.this)
//				.setMessage("Error in parsing data!")  
//				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//					public void onClick(DialogInterface dialog, int id) {
//					}
//				})
//				.show();
//				Log.e("log_tag", "Error parsing data "+e.toString());
			}
		}
		
		//Set Click Listener
		btnReply.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				String text = reply.getText().toString();
				
				//SharedPreferences user = getSharedPreferences("Users", MODE_PRIVATE);
		        //String id = user.getString("CurrentUser", null);
				
				String r = reply(P_id,id,cat,text);
				//result.setText(r);
				Intent myIntent = new Intent(v.getContext(), BuySell.class);
				startActivityForResult(myIntent, 0);
			
				lblResult.setText(r);
				
				Toast.makeText(
						getApplicationContext(),
						"Reply sent!",
						Toast.LENGTH_SHORT)
						.show();
				
				//Intent myIntent = new Intent(v.getContext(), TabMain.class);
				//startActivityForResult(myIntent, 0);
				finish();
			}
		});
	}
	
public static final String THREAD = "http://www.upennakpsi.org/lololol/pennmarketplace/getthread.php";
	
	private String getThread (String id, String U_id, String P_id) {

		InputStream is = null;

		String result = "";
		//LinkedList<String> listings = new LinkedList<String>();

		//the postings
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("id",id));
		nameValuePairs.add(new BasicNameValuePair("U_id",U_id));
		nameValuePairs.add(new BasicNameValuePair("P_id",P_id));
		//nameValuePairs.add(new BasicNameValuePair("text",text));

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(THREAD);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);            
			HttpEntity entity = response.getEntity();
			is = entity.getContent();                

		}catch(Exception e){
			//listings.add("Error in connecting...");
			result = "Error in connecting...";
			Log.e("log_tag", "Error in http connection "+e.toString());
			return result;
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			result = "Error in obtaining data...";
			Log.e("log_tag", "Error converting result "+e.toString());
			return result;
		}
		
		return result;
	}
	
public static final String REPLY = "http://www.upennakpsi.org/lololol/pennmarketplace/reply.php";
	
	private String reply (String id, String U_id, String cat, String text) {

		InputStream is = null;

		String result = "";
		//LinkedList<String> listings = new LinkedList<String>();

		//the postings
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("id",id));
		nameValuePairs.add(new BasicNameValuePair("U_id",U_id));
		nameValuePairs.add(new BasicNameValuePair("cat",cat));
		nameValuePairs.add(new BasicNameValuePair("text",text));

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(REPLY);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);            
			HttpEntity entity = response.getEntity();
			is = entity.getContent();                

		}catch(Exception e){
			//listings.add("Error in connecting...");
			result = "Error in connecting...";
			Log.e("log_tag", "Error in http connection "+e.toString());
			return result;
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			result = "Error in obtaining data...";
			Log.e("log_tag", "Error converting result "+e.toString());
			return result;
		}
		
		return result;
	}
	
public static final String USER = "http://www.upennakpsi.org/lololol/pennmarketplace/getusername.php";
	
	private String getUsername (String id) {

		InputStream is = null;

		String result = "";
		//LinkedList<String> listings = new LinkedList<String>();

		//the postings
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("id",id));
		//nameValuePairs.add(new BasicNameValuePair("U_id",U_id));
		//nameValuePairs.add(new BasicNameValuePair("P_id",P_id));
		//nameValuePairs.add(new BasicNameValuePair("text",text));

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(USER);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);            
			HttpEntity entity = response.getEntity();
			is = entity.getContent();                

		}catch(Exception e){
			//listings.add("Error in connecting...");
			result = "Error in connecting...";
			Log.e("log_tag", "Error in http connection "+e.toString());
			return result;
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			result = "Error in obtaining data...";
			Log.e("log_tag", "Error converting result "+e.toString());
			return result;
		}
		
		return result;
	}
	
   /* @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
		case R.id.preferences:
			startActivity(new Intent(this, Prefs.class));
			return true; 
			
		case R.id.logout:
			//IMPLEMENT LOGOUT HERE
			
			Toast.makeText(
					getApplicationContext(),
					"Successfully Logged Out!",
					Toast.LENGTH_SHORT)
					.show();
			Intent myIntent = new Intent(ReplyThread.this, Intro.class);
			startActivityForResult(myIntent, 0);
			
			
//			new AlertDialog.Builder(Reply.this)
//			//.setTitle(Register.this.getResources().getString(R.string.register_alert))  
//			.setMessage("Successfully Logged Out!")  
//			//.setIcon(R.drawable.book)  
//			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//				public void onClick(DialogInterface dialog, int id) {
//					Intent myIntent = new Intent(Reply.this, Intro.class);
//					startActivityForResult(myIntent, 0);
//				}
//			})
//			.show();
			
			return true;
    	}
    	return false;
    }*/

}
